package cn.xjt.screenShare.tcp;

import cn.xjt.screenShare.constant.EnumConstant;
import cn.xjt.screenShare.util.ImageUtil;
import lombok.Data;
import lombok.SneakyThrows;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xujiangtao
 * @version 1.0
 * @description tcp服务器
 * @date 2022/8/16 23:06
 */
@Data
public class TcpServer{

    private ExecutorService executorServices = Executors.newCachedThreadPool();
    private static TcpServer tcpServer = new TcpServer();

    public static TcpServer getInstance(){
        return tcpServer;
    }

    @SneakyThrows
    public void start() {
        ServerSocket socket = new ServerSocket(EnumConstant.Port.SERVER.port);
        System.out.println("服务器启动成功,等待连接...");
        while (true)
        {
            Socket client = socket.accept();
            System.out.println("获取到一个连接...");
            //开启多个线程
            executorServices.submit(() -> {
                OutputStream os = null;
                try {
                    while (true){
                        os = client.getOutputStream();
                        byte[] bytes = ImageUtil.catScreen();
                        System.out.println("长度"+bytes.length);
                        os.write(bytes);
                        os.flush();
                    }
                } catch (Exception e) {
                    System.out.println("断开一个连接:"+e.getMessage());
                }
            });
        }
    }

    public static void main(String[] args) {
        TcpServer tcpServer = TcpServer.getInstance();
        tcpServer.start();
    }
}
